<?
// function will check for sel_format and will return return the dates array 
// within the date rangepassed

function getPureDaysoff($fromdate, $todate, $table, $staffid="0")
{
	$days = array();

	$result = getCompanyOff($fromdate, $todate, $table, $staffid);
	
	$fromdate_t = strtotime($fromdate); 
	$todate_t = strtotime($todate); 

	while($row = mysql_fetch_object($result))
	{
		if($row->sel_format == 1)	{
			$days[] = $row->date;
		} else if($row->sel_format == 2) {
			$date = explode("-",$row->date);
			$date = $date[2];
			$days[] = date("Y",$fromdate_t)."-".date("m",$fromdate_t)."-".$date;
	
			if( date("m",$fromdate_t) != date("m",$todate_t) )
				$days[] = date("Y",$todate_t)."-".date("m",$todate_t)."-".$date;
		} else if($row->sel_format == 3) {
			$days[] = date("w",strtotime($row->date));
		} else {
			list($year,$month,$day) = split("-",$row->date);
			$days[] = date("Y",$fromdate_t)."-".$month."-".$day;
		}
	}
	
	return $days;
}

function getCompanyOff($fromdate, $todate,$table,$staffid="0")
{
	if($table == "staff") {
		$staffquery = " and staff_id in ('".$staffid."') ";
	}

	$query = "select date,sel_format from ".$table."_offdays where 
			business_id='".$_SESSION['business_id']."' $staffquery and 
			(
			sel_format=3 or sel_format=2 or
			( (date between '".$fromdate."' and '".$todate."') and sel_format=1) or
			( ( dayofyear(date) >= dayofyear('".$fromdate."') and dayofyear(date) <= dayofyear('".$todate."') ) 
			and sel_format=4 )
			
			)";

	$result = query($query);
	return $result;
}


// shows a date on the calendar
function dateCell($date,$notavail,$calurl,$tstamp)
{
	$classname="calDay";
	$classReserved = "calDayReserved";

	if($tstamp!="" && $date!="") {
	if(date("Y-m-d",$tstamp) == date("Y-m-d",$date))
		$classname="calToday";
	}
	if($date != "") {
	if($notavail == "")	
		$td = "<td class='$classname'><a href='".$calurl."?stamp=".$date."&staff_id=".$_GET['staff_id']."' class='calDay'>".date("d",$date)."</a></td>"."\n";
	else 
		$td = "<td class='$classReserved'>".date("d",$date)."</td>"."\n";
	} else 
		$td = "<td class='$classname'></td>"."\n";
	return $td;
}

function query($query,$extra="")
{
	$result = mysql_query($query) or die("Query execution error : ".mysql_error()."<br> Query : $query <br> Query Type : $extra");
	return $result;
}

function showStaffSelect($staffid="",$url="")
{	
	if (!is_numeric($staff_id))
		$staff_id = "";	
	
	if($url=="")
		$url = $_SERVER['PHP_SELF'];

	$query = "select * from staff where business_id='".$_SESSION['business_id']."' and status=1";
	$results = query($query,"staff memeber selection");

	?>
	<select id="selectstaff" name="selectstaff" onChange="location.href='<?=$url ?>?staff_id='+this.value">
	<option value="0">Select a Staff Member</option>
	<option value="0">No Preference</option>
	<?
		while( $row = mysql_fetch_object($results))
		{
			if($staff_id == $row->staff_id) 
				$select="selected";
			else 
				$select="";
			echo "<option value='".$row->staff_id."' $select>$row->first_name</option>\n";
		}
	?>
	</select>
	<?

}

function staffListForm($staffid, $flag=1) {
	$query = "select staff_id,first_name from staff where business_id='".$_SESSION['business_id']."' and status=1 order by first_name";
	$results = query($query,"staff memeber selection");
	if($flag!=1) {
		$js = 'onChange="ajaxGetServices(this.value)"';
	}
	?>
	<select name="staff_id" id="staff_id" <?=$js?>>
	<option value="0">Select a Staff Member</option>
	<?
		while( $row = mysql_fetch_object($results))
		{
			if($staffid == $row->staff_id) 
				$select="selected";
			else 
				$select="";
			echo "<option value='".$row->staff_id."' $select>$row->first_name</option>\n";
		}
	?>
	</select>
	<?
}

function customerListForm($customerid, $noajax=0) {
	$query = "select customer_id,firstname,lastname from customer_info where business_id='".$_SESSION['business_id']."' and status=1 order by firstname";
	$results = query($query);
	$text = "All Customers";
	if($noajax==0) {
		$ajax= 'onChange="ajaxGetCustomer(this.value)"';
		$text = "New Customer";
	} 
	?>
	<select  name="customer_id" id="customer_id" <?=$ajax?>>
	<option value="0"><?=$text?></option>
	<?
		while( $row = mysql_fetch_object($results))
		{
			if($customerid == $row->customer_id) 
				$select="selected";
			else 
				$select="";
			echo "<option value='".$row->customer_id."' $select>".substr("$row->firstname $row->lastname",0,14)."</option>\n";
		}
	?>
	</select>
	<?
}

function serviceListForm($service_id) {
	$query = "select service_id, title from services where business_id='".$_SESSION['business_id']."' order by title";
	$results = query($query);
	?>
	<select  name="service_id" id="service_id" onChange="ajaxGetService(this.value)">
	<option value="">Select Service</option>
	<?
		while( $row = mysql_fetch_object($results))
		{
			if($row->service_id==$service_id) {
				$sel = "selected";
			} else {
				$sel = "";
			}

			echo "<option value='".$row->service_id."' $sel>$row->title</option>\n";
		}
	?>
	</select>
	<?
}

function getAppointmentTime() {
 	$business_id = $_SESSION['business_id'];
 	$query = "select setting_value from appointment_setting where 
	setting_name='appointment_start' and business_id='$business_id'";
	$setting = mysql_fetch_object(query($query));
	return $setting->setting_value;
 }
 

 
  function getOfficeHours() {
 	$business_id = $_SESSION['business_id'];
 	$query = "select * from hours_management where business_id=$business_id";
	$hrs = mysql_fetch_object(query($query));
	$weekday = array('monday','tuesday','wednesday','thursday','friday','saturday','sunday');

	foreach($weekday as $day) {
		if($hrs->$day == 1) {
			$fromname = $day."from";
			
			$temp = strtotime(date("Y-m-d")." ".$hrs->$fromname);
			$from[] = $temp;
			
			$toname = $day."to";
			$temp = strtotime(date("Y-m-d")." ".$hrs->$toname);
			$to[] = $temp;
		}
	}
	if(count($from)==0 or count($to)==0) {
		return;
	}
	
	$from = min($from);
	$to = max($to);

 	$arr['start_time'] = $from;
	$arr['end_time'] = $to;
	return $arr;
 }
 
  function listDurationForm($duration) {
	?>
	<select  name="duration" id="duration">
	<?
	$i=1;
	if($duration == "") {
		$duration = 3600;
	}
	
	$start = $duration;
	$end = 480;
	while($start<=$end)
	{	
		if($start>=60) {
			$hrs = floor($start / 60) . " hrs";
			$mins = ($start % 60) ." min(s)";

		} else {
			$hrs = "";
			$mins = $start." mins";
		}
		
		echo "<option value='".($start)."'>$hrs $mins</option>\n";
		$start= $start + $duration;
	}
	?>
	</select>
	<?
 }
 
 function statusListForm($as_id,$update=0) {
	$query = "select * from appointment_status_type where (business_id='".$_SESSION['business_id']."' or business_id='0') order by sortorder";
	$results = query($query);
	?>
	<select  name="apptstatus" id="apptstatus">
	<option value="">Select Status</option>
	<?
		while( $row = mysql_fetch_object($results))
		{
			if($row->as_id == $as_id) {
				$sel = "selected";
			} else {
				$sel = "";
			}
			echo "<option value='".$row->as_id."' style='background-color:".$row->color."' $sel>$row->description</option>\n";
		}
	?>
	</select>
	<?
}

function startTimeListForm($arr, $interval, $stamp) {
	?>
	<select  name="starttime" id="starttime">
	<?
	
	$start = $arr['start_time'];
	$end = $arr['end_time'];
	$i=1;
	if($start == "") {
		$start=30;
	}
	
	$interval = $interval * 60;
	
	while($start<$end)
	{			
		if(date("H:i",$start) == date("H:i",$stamp)) {
			$selected = "selected";
		} else {
			$selected = "";
		}
		echo "<option value='".($start)."' $selected>".date("H:i",$start)."</option>\n";
		$start= $start + $interval;
	}
	?>
	</select>
	<?
}

function chkCustomer($email) {
	$business_id = $_SESSION['business_id'];
	$query = "select customer_id from customer_info where email ='".$email."' and business_id='$business_id' and status='1'";
	$res = query($query);
	$num = mysql_num_rows($res);
	if($num > 0) 
		return true;
	else 
		return false;
}

function finalizeApp($obj) {
	$business_id = $_SESSION['business_id'];

	$dateadded = date("Y-m-d");
	$createdby = $_SESSION['administrator_id'];
	
	$fields = array('business_id','customer_id','staff_id','service_id','duration','apptdate','starttime', 'endtime' ,'apptstatus','cost','tip','customernotes','specialinstruction', 'apptnotes','appttype','customeremailstatus', 'staffemailstatus','dateadded','createdby');

	if($obj['appt_id']!="") {
	foreach($fields as $f) {
		if($obj[$f]!='') {
			$val = $obj[$f]; 
		} elseif($$f!='') {
			$val = $$f;
		}

		$final = $final. $f.'='."'".$val."',"."\n";
	}
	$final = substr($final,0,strlen($final)-2);
	$query = "update finalize_appointment set $final where appt_id='".$obj['appt_id']."'";
	query($query);
	return 'Appointment Updated Successfully';
	exit;	
	}


// code for insert
	foreach($fields as $f) {
		if($obj[$f]!='') {

			$field = $field."$f,";
			$values = $values."'$obj[$f]',";
		} elseif($$f!='') {
		
			$field = $field."$f,";
			$values = $values."'".$$f."',";
		}
	}

	$field = substr($field,0,strlen($field)-1);
	$values = substr($values,0,strlen($values)-1);
		
	$query = "insert into finalize_appointment($field) values($values)";
	if(query($query)) {
		return 'Appointment added successfully';
	}

}

function createCustomer($obj) {
	$business_id = $_SESSION['business_id'];
	$status = "1";
	$fields = array('firstname','lastname','address','city','state','zipcode','dayphone','eveningphone','email','cellphone','username','password','business_id','status');
	$password = $obj['firstname'];
	$username = $obj['email'];
	foreach($fields as $f) {
		if($obj[$f]!='') {
			$field = $field."$f,";
			$values = $values."'$obj[$f]',";
		} elseif($$f!='') {
			$field = $field."$f,";
			$values = $values."'".$$f."',";
		}
	}
	$field = substr($field,0,strlen($field)-1);
	$values = substr($values,0,strlen($values)-1);
		
	$query = "insert into customer_info($field) values($values)";
	if(query($query)) {
		return mysql_insert_id();
	}

}

function getCustomer($customer_id) {
	$business_id = $_SESSION['business_id'];
	$status = "1";
	$fields = "firstname,lastname,address,city,state,zipcode,dayphone,eveningphone,email,cellphone";

	$query = "select $fields from customer_info where customer_id='$customer_id' and 
				business_id='$business_id' and status='$status'";
	$res = query($query);
	//return mysql_fetch_object($res);
	$obj = mysql_fetch_object($res);
	return $obj;
}

function getService($service_id) {
	$business_id = $_SESSION['business_id'];
	$status = "1";
	$fields = "duration,cost";

	$query = "select $fields from services where service_id='$service_id' and 
				business_id='$business_id'";
	$res = query($query);
	//return mysql_fetch_object($res);
	$obj = mysql_fetch_object($res);
	return $obj;
}

function checkHoliday($starttime) {
	$startdate = date("Y-m-d",$starttime);
	$enddate = date("Y-m-d",$starttime);
	$companyOff = getPureDaysoff($startdate,$enddate,'company');

	if(in_array($startdate,$companyOff) or in_array(date("w",$starttime),$companyOff)) {
		return false;
	}
	return true;
}

function checkStaffOffDay($starttime,$staffid) {
	$startdate = date("Y-m-d",$starttime);
	$enddate = date("Y-m-d",$starttime);
	$companyOff = getPureDaysoff($startdate,$enddate,'staff',$staffid);

	if(in_array($startdate,$companyOff) or in_array(date("w",$starttime),$companyOff)) {
		return false;
	}
	return true;
}

function appointmentExists($obj) {
	$starttime = $obj['starttime'] + 1;
	$endtime = $obj['endtime'] - 1;
	$status = $obj['apptstatus'];
	
	if($obj['appt_id']!="") {
		$extra = " and appt_id!='".$obj['appt_id']."'";
	}

	if($status==0) {
		$statusquery = " and apptstatus='0'";
	}
	$staff_id = $obj['staff_id'];
	$business_id = $_SESSION['business_id'];
	$query = "select * from finalize_appointment where 
			 (
			'$starttime' between starttime and endtime
			or 
			'$endtime' between starttime and endtime
			)
			and apptstatus = '$status'
			$statusquery
			and business_id='$business_id'
			and staff_id = '$staff_id'
			$extra";
	$res = query($query);
	$num = mysql_num_rows($res);
	if($num>=1) {
		return true;	
	}
	return false;
	
}

function validateAppointmentAdd($obj) {

	if($obj['customer_id']=='') {
		return 'Some error has occured.';
	}

	if(!checkHoliday($obj['starttime'])) {
		return "Premises is not open on selected day. Please choose another day.";
	}

	if(!checkStaffOffDay($obj['starttime'],$obj['staff_id'])) {
		return "Selected staff memeber is on leave on the selected day. Choose another staff memeber.";
	}

	if(appointmentExists($obj)) {
		return "There is already an appointment scheduled in the selected duration.";
	}
	
	//checkOfficeHrs($starttime,$endtime);
	//checkDateAvailable($startime,$endtime);
	//checkTimeAvailable($starttime,$endtime);
	//return 'Testing is going on';
}

function getAppointments($date,$apptid=0) {
	$date = date("Y-m-d",$date);
	
	if($apptid!=0) {
		$extra = " and app.appt_id='$apptid'";
	}
	$business_id = $_SESSION['business_id'];
	
	$query = "select app.*,cus.firstname,cus.lastname,
			  st.first_name, st.last_name,ser.title,
			  stat.color,stat.description
			  from finalize_appointment as app 
			  left join customer_info as cus on app.customer_id=cus.customer_id
			  left join staff as st on st.staff_id=app.staff_id
			  left join services as ser on ser.service_id=app.service_id
			  left join appointment_status_type as stat on stat.as_id = app.apptstatus
			where app.apptdate='$date' and app.apptstatus!='1' and app.business_id='$business_id'
			$extra order by starttime,staff_id";
	$res = query($query);
	return $res;
}

?>